package com.hmall.item.web;

import com.hmall.common.dto.ItemDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.result.Result;
import com.hmall.common.vo.PageVo;
import com.hmall.item.service.IItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;


    /**
     * 分页查询商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageVo<Item> pageQuery(@RequestParam("page") Long page,@RequestParam("size") Long size){
        PageVo pageVo = itemService.pageQuery(page,size);
        return pageVo;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item findItemById(@PathVariable("id") Long id){
         Item item = itemService.findItemById(id);
        return item;
    }
    @GetMapping("/order/{id}")
    public Item selectItemById(@PathVariable("id") Long id){
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 新增商品
     * @param itemDTO
     * @return
     */
    @PostMapping
    public Result<Item> save(@RequestBody ItemDTO itemDTO){
        Item item = new Item();
        BeanUtils.copyProperties(itemDTO,item);
        itemService.save(item);
        return Result.success();
    }

    @PutMapping("/status/{id}/{status}")
    public Result<Item> updateStatus(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        itemService.updateEs(item);
        return Result.success();
    }
    @PutMapping
    public Result<Item> update(@RequestBody ItemDTO itemDTO){
        Item item = new Item();
        BeanUtils.copyProperties(itemDTO,item);
        Item itemById = itemService.findItemById(item.getId());
        itemById.setUpdateTime(null);
        itemService.updateById(item);

        return Result.success();
    }
    @DeleteMapping("{id}")
    public Result<Item> deleteById(@PathVariable("id") Long id){
        itemService.removeById(id);
        return Result.success();
    }

    /**
     * 修改库存接口
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void updateStock(@PathVariable(value = "itemId")Long itemId,
                            @PathVariable(value = "num")Integer num){
        Item item = itemService.getById(itemId);
        item.setStock(item.getStock()-num);
        itemService.updateById(item);
    }
}
